import request from '@/utils/request'
import type { AxiosResponse } from 'axios'

interface EmotionResponse {
  score: number;
  lstmScore: number;
  riskLevel: string;
}

interface RealtimeEmotionResponse {
  score: number;
  lstmScore: number;
  riskLevel: string;
  timestamp?: string;
}

// 分析聊天内容的情感
export async function analyzeEmotion(content: string, userId: number, messageId?: number): Promise<EmotionResponse & { message?: string }> {
  try {
    console.log('开始情感分析，内容:', content, '用户ID:', userId, '消息ID:', messageId)
    const response = await request({
      url: '/emotion/analyze',
      method: 'post',
      data: { 
        content, 
        userId,
        messageId 
      }
    })
    
    console.log('情感分析完整响应:', response)
    
    // 检查响应数据
    const data = response as unknown as EmotionResponse
    if (data && typeof data.score === 'number' && data.riskLevel) {
      console.log('成功获取情感分析结果:', data)
      return {
        score: data.score,
        lstmScore: data.lstmScore,
        riskLevel: data.riskLevel,
        message: '分析成功'
      }
    }
    
    console.warn('情感分析响应格式不正确:', response)
    return {
      score: 0.5,
      lstmScore: 0.5,
      riskLevel: 'UNKNOWN',
      message: '分析结果格式不正确'
    }
  } catch (error: any) {
    console.error('情感分析失败:', error)
    const errorMessage = error.response?.data?.error || error.message || '操作失败'
    return {
      score: 0.5,
      lstmScore: 0.5,
      riskLevel: 'UNKNOWN',
      message: errorMessage
    }
  }
}

// 获取用户的情感分析历史
export function getEmotionHistory(userId: number) {
  console.log('获取情感分析历史，用户ID:', userId)
  return request({
    url: '/emotion/history',
    method: 'get',
    params: { userId }
  }).then(response => {
    console.log('获取历史响应:', response)
    if (!response.data) {
      console.warn('获取历史数据为空，返回空数组')
      return []
    }
    return response.data
  }).catch(error => {
    console.error('获取历史错误:', error.response || error)
    return []  // 返回空数组而不是抛出错误
  })
}

// 获取实时情感分析结果
export function getRealtimeEmotion(userId: number): Promise<RealtimeEmotionResponse> {
  console.log('获取实时情感分析，用户ID:', userId)
  return request({
    url: '/emotion/realtime',
    method: 'get',
    params: { userId }
  }).then((response: any) => {
    console.log('获取实时分析响应:', response)
    if (!response || response.score === undefined) {
      console.warn('实时情感数据为空，使用默认值')
      return {
        score: 0.5,
        lstmScore: 0.5,
        riskLevel: 'LOW',
        timestamp: null
      }
    }
    return response
  }).catch(error => {
    console.error('获取实时情感错误:', error)
    return {
      score: 0.5,
      lstmScore: 0.5,
      riskLevel: 'LOW',
      timestamp: null
    }
  })
} 